#!/usr/bin/python
# coding:utf-8

import requests
import json
import time
import openpyxl
from retrying import retry

array = [] # 待查询数组

HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}

LOGIN_URL = 'http://'
LOGIN_DATA = {}

SEARCH_URL = 'http://'
SEARCH_DATA = {}

def Get_Session(URL, DATA, HEADERS):
    ROOM_SESSION = requests.Session()
    ROOM_SESSION.post(URL, data=DATA, headers=HEADERS)
    return ROOM_SESSION

@retry(stop_max_attempt_number=3) # 最大重试3次，3次全部报错，才会报错
def _parse_url(data):
    response = SESSION.post(SEARCH_URL, data=data, headers=HEADERS, timeout=15) # 超时的时候回报错并重试
    assert response.status_code == 200 # 状态码不是200，也会报错并重试
    return response

def parse_url():
    row = 2 # 查询写入数据
    for data in array:
        try: # 进行异常捕获
            SEARCH_DATA = {}
            RES = _parse_url(SEARCH_DATA)
            RES.encoding = 'GBK'

            JSON = json.loads(RES.text)

            if JSON['result']:
                sheet.cell(row=row, column=1, value=str(data))
                sheet.cell(row=row, column=2, value=str(JSON['data']))
            else:
                sheet.cell(row=row, column=1, value=str(data))
                sheet.cell(row=row, column=2, value=str(JSON['errMsg']))
        except Exception as e:
            sheet.cell(row=row, column=1, value=str(data))
            sheet.cell(row=row, column=2, value=str(e))

        row += 1
        print("写入计数：", row - 2)
        time.sleep(0.1)


# 新建 excel
wbname = "dist.xlsx"
wb = openpyxl.Workbook()
wb.save(wbname)
print("新建Excel：" + wbname + "成功")

wb = openpyxl.load_workbook(wbname)
sheet = wb.active
sheet.title = time.strftime("%Y-%m-%d %H.%M.%S", time.localtime())

# 写入表头
fields = ['数据', '结果']
field = 1
for field in range(1, len(fields) + 1):
    sheet.cell(row=1, column=field, value=str(fields[field - 1]))

# 获取 SESSION
SESSION = Get_Session(LOGIN_URL, {}, HEADERS)

# 获取数据
parse_url()

# 保存 excel
wb.save(wbname)
print("保存成功")
